package com.cyys.modules.system.controller.user;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cyys.common.annotation.SystemLog;
import com.cyys.common.dataScope.DataScope;
import com.cyys.common.ql.AR;
import com.cyys.common.ql.JSONData;
import com.cyys.common.utils.list.ListUtil;
import com.cyys.common.validate.Detail;
import com.cyys.common.validate.Edit;
import com.cyys.common.validate.Insert;
import com.cyys.modules.core.controller.BaseAction;
import com.cyys.modules.core.sysParam.SystemConfigureUtil;
import com.cyys.modules.core.sysParam.SystemConstants;
import com.cyys.modules.system.model.user.Menu;
import com.cyys.modules.system.model.user.Role;
import com.cyys.modules.system.service.user.MenuService;
import com.cyys.modules.system.service.user.RoleService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/sys/role")
public class RoleAction extends BaseAction {

	@Resource
	private RoleService roleService;

	@Resource
	private MenuService menuService;

	@GetMapping("/add/input")
	public String input(String orgId, Model model)  {
		Role role = new Role();
		String roleScope = getUser().getType();
		if("3".equals(roleScope)){ //本机构权限
			orgId= getUser().getOrgId();
		}
		role.setOrgId(orgId);
		model.addAttribute("role", role);
		model.addAttribute("userType",getUser().getType());
		return "module/system/user/role-input";
	}

	@ResponseBody
	@PostMapping("/add/save")
	@SystemLog(module = "系统设置", methods = "角色管理-保存角色")
	public AR save(@Validated(Insert.class) Role role, Model model)  {
		return roleService.save(role);
	}

	@GetMapping("/edit/input")
	public String editInput(@Validated(Detail.class) Role role, Model model)  {
		model.addAttribute("userType",getUser().getType());
		model.addAttribute("role", roleService.getById(role.getId()));
		return "module/system/user/role-input";
	}

	@ResponseBody
	@PostMapping("/edit/save")
	@SystemLog(module = "系统设置", methods = "角色管理-更新角色")
	public AR update(@Validated(Edit.class) Role role, Model model)  {
		return roleService.update(role);
	}

	@ResponseBody
	@PostMapping("/del/deleteById")
	@SystemLog(module = "系统设置", methods = "角色管理-删除角色")
	public AR deleteById(String id)  {
		return roleService.deleteById(id);
	}

	@ResponseBody
	@PostMapping("/del/deleteByIds")
	@SystemLog(module = "系统设置", methods = "角色管理-批量删除角色")
	public AR deleteByIds(String ids)  {
		return roleService.deleteBatchIds(ids);
	}

	@GetMapping("/list")
	@RequiresPermissions("sys:role:list")
	public String list(Model model)  {
		Boolean mutiOrg = Boolean.valueOf(SystemConfigureUtil.get(SystemConstants.MUTI_ORG));
		if(mutiOrg) {    //是否开启机构管理
			String roleScope = getUser().getType();
			//超管 或 所有机构权限 或 本机构及本机构下级权限 或 自定义机构  时显示机构树结构
			if("1".equals(getUser().getId()) || "1".equals(roleScope) || "2".equals(roleScope) || "4".equals(roleScope)){
				return "module/system/user/role-org-list";
			}else{
				model.addAttribute("orgId", getUser().getOrgId());
			}
		}
		return "module/system/user/role-list";
	}

	@ResponseBody
	@PostMapping("/list/listInfo")
	@SystemLog(module = "系统设置", methods = "角色管理-查询角色")
	public String rolelist(Role role, Page page, Model model)  {
		Boolean mutiOrg = Boolean.valueOf(SystemConfigureUtil.get(SystemConstants.MUTI_ORG));
		if(mutiOrg) { //是否开启机构管理
			QueryWrapper qw= new QueryWrapper(role);
			qw.orderByDesc("date_create");
			return JSONData.toLayerData(roleService.selectPageByScope(page , qw, new DataScope()));
		}
		return JSONData.toLayerData(roleService.list(page , new QueryWrapper(role),true));
	}

	@GetMapping("/add/setAuthority")
	public String setAuthority(String roleId, Model model)  {
		model.addAttribute("roleId", roleId);
		return "module/system/user/set-authority";
	}

	@ResponseBody
	@PostMapping("/add/menuAuthority")
	public String menuAuthority(String roleId,Boolean extendAll)  {
		Role role = roleService.getById(roleId);
		Map<String, Menu> menuMap = (Map<String, Menu>) ListUtil.listToMap(role.getMenuList());
		List<Menu> menuList = menuService.listAllTree(null);
		String menuArray = "[";
		if(getUser().getType().equals("1")) {
			menuArray += getMenuArray(menuList, menuMap,extendAll);
		}else{
			Map<String, Menu> userMenuMap = (Map<String, Menu>) ListUtil.listToMap(getUser().getMenuList());
			menuArray += getMenuArrayByUserId(menuList, menuMap, userMenuMap);
		}
		int indx = menuArray.lastIndexOf(",");
		if (indx != -1)
			menuArray = menuArray.substring(0, indx);
		menuArray += "]";
		return menuArray;
	}

	private String getMenuArrayByUserId(List<?> list, Map<String, ?> map, Map<String, ?> userMenuMap) {
		String menuArray = "";
		if(userMenuMap != null) {
			for (int i = 0; i < list.size(); i++) {
				Menu t = (Menu) list.get(i);
				Menu um = (Menu) userMenuMap.get(t.getId());
				if (um != null) {
					menuArray += "{id:\"" + t.getId() + "\"," + "pId:\"" + t.getParentId() + "\",name:\"" + t.getName() + "\"";
					if (map != null) {
						Menu m = (Menu) map.get(t.getId());
						if (m != null) {
							menuArray += ",checked:true";
						}
					}
					if (t.getHasChild() == 1) {
						menuArray += ",isParent:true";
					}
					if (t.getChildren() != null && t.getChildren().size() > 0) {
						menuArray += ",open:true},";
						menuArray += getMenuArrayByUserId(t.getChildren(), map, userMenuMap);
					} else {
						menuArray += "},";
					}
				}
			}
		}
		return menuArray;
	}

	private String getMenuArray(List<?> list, Map<String, ?> map,Boolean extendAll) {
		String menuArray = "";
		for (int i = 0; i < list.size(); i++) {
			Menu t = (Menu) list.get(i);
			menuArray += "{id:\"" + t.getId() + "\"," + "pId:\"" + t.getParentId() + "\",name:\"" + t.getName() + "\"";
			if (map != null) {
				Menu m = (Menu) map.get(t.getId());
				if (m != null) {
					menuArray += ",checked:true";
				}
			}
			if (t.getHasChild() == 1) {
				menuArray += ",isParent:true";
			}
			if (t.getChildren() != null && t.getChildren().size() > 0) {
				menuArray += ",open:true},";
				menuArray += getMenuArray(t.getChildren(), map, extendAll);
			} else {
				menuArray += "},";
			}
		}
		return menuArray;
	}

	@ResponseBody
	@PostMapping("/add/setMenuRole")
	public AR setMenuRole(String roleId, String menuIds)  {
		menuService.setMenuRole(roleId, menuIds);
		return AR.ok("设置成功");
	}
}
